import React, {PureComponent} from "react";
import {Button, Form, Icon, Input, InputNumber, notification, Select, Table} from "antd";
import {tableProps} from "../../lib/ui";
import {updateBaoGuanFee, updateFeeList} from "./actions";
import {connect} from "react-redux";

const {Option} = Select;
const EditableContext = React.createContext();

const EditableRow = ({form, index, ...props}) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({editing}, () => {
            if (editing) {
                this.input.focus();
            }
        });
    };

    save = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            }
            this.toggleEdit();
            handleSave({...record, ...values});
        });
    };

    saveCurrency = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e]) {
                return;
            }
            this.toggleEdit();
            values.currency = e;
            handleSave({...record, ...values});
        });
    };

    renderCell = form => {
        this.form = form;
        const {children, dataIndex, record, inputType, options = [], placeholder} = this.props;
        const {editing} = this.state;
        let column;
        if (inputType === "number") {
            column = <InputNumber ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>;
        } else if (inputType === "select") {
            column = <Select placeholder={placeholder} ref={node => (this.input = node)} style={{width: 180}}
                             onChange={this.saveCurrency} allowClear={true}>
                {options.map((item, index) => (
                    <Option key={index} value={item.name}>
                        {item.name}
                    </Option>
                ))}
            </Select>;
        } else {
            column = <Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>;
        }
        return editing ? (
            <Form.Item style={{margin: 0}}>
                {form.getFieldDecorator(dataIndex, {
                    initialValue: record[dataIndex],
                })(column)}
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{paddingRight: 24}}
                onClick={this.toggleEdit}
            >
                {children}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            inputType,
            options,
            placeholder,
            handleSave,
            children,
            valueField,
            labelField,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}

class ClientFeeModal extends PureComponent {

    handleSave = values => {
        const {dispatch, feeList} = this.props;
        const found = feeList.find(fee => fee.id === values.id);
        const exist = feeList.find(fee => fee.id !== values.id && fee.feeName === values.feeName);
        if (exist) {
            notification.error({
                message: '存在相同科目的费用,不能添加'
            });
            dispatch(updateFeeList(feeList));
            return;
        }
        if (found) {
            found.feeName = values.feeName;
            found.feeCount = values.feeCount;
            found.currency = values.currency;
        } else {
            feeList.push(values);
        }
        dispatch(updateFeeList(feeList));

    };

    handleAddFeeName = () => {
        const {dispatch, feeList} = this.props;
        feeList.push({
            "id": Math.random().toString(),
            "feeName": "",
            "feeCount": 0,
            "currency": undefined
        });
        dispatch(updateFeeList(feeList));
    };

    handleDeleteFee = record => {
        const {dispatch, feeList} = this.props;
        const deleteIndex = feeList.findIndex(item => item.id === record.id);
        feeList.splice(deleteIndex, 1);
        dispatch(updateFeeList(feeList));
    };

    onChangeHomeFee = value => {
        const {dispatch, sheetFee, currency, sheetCurrency} = this.props;
        dispatch(updateBaoGuanFee({homeFee: value, sheetFee, currency, sheetCurrency}));
    };

    changeCurrency = value => {
        const {dispatch, sheetFee, homeFee, sheetCurrency} = this.props;
        dispatch(updateBaoGuanFee({currency: value, sheetFee, homeFee, sheetCurrency}));
    };
    changeSheetCurrency = value => {
        const {dispatch, sheetFee, homeFee, currency} = this.props;
        dispatch(updateBaoGuanFee({currency, sheetFee, homeFee, sheetCurrency: value}));
    };
    onChangeSheetFee = value => {
        const {dispatch, homeFee, currency, sheetCurrency} = this.props;
        dispatch(updateBaoGuanFee({homeFee, sheetFee: value, currency, sheetCurrency}));
    };

    render() {
        const {loading, feeList, currencyList, homeFee, sheetFee, currency, sheetCurrency} = this.props;
        const columns = [
            {
                title: "费用科目",
                dataIndex: "feeName",
                editable: true,
                width: "150px",
            }, {
                title: "金额",
                dataIndex: "feeCount",
                editable: true,
                inputType: "number",
                width: "150px",
            }, {
                title: "币种",
                dataIndex: "currency",
                editable: true,
                inputType: "select",
                options: currencyList,
                placeholder: "请选择币种",
                width: "150px",
            }, {
                title: '功能',
                dataIndex: '',
                key: 'x',
                render: (text, record) => <a onClick={() => this.handleDeleteFee(record)}>删除费用</a>
            }
        ];
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        const editColumns = columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    options: col.options,
                    placeholder: col.placeholder,
                    inputType: col.inputType,
                    handleSave: this.handleSave,
                }),
            };
        });
        // 过滤报关费
        const data = [];
        feeList.forEach(item => {
            if ("报关费" !== item.feeName) {
                data.push(item);
            }
        });
        return (
            <div>
                <div className="actions2">
                    主页费币种：<Select placeholder="请选择币种" value={currency} onChange={this.changeCurrency}
                               style={{width: "100px"}}>
                    {currencyList.map((item, index) => (
                        <Option key={index} value={item.name}>
                            {item.name}
                        </Option>
                    ))}
                </Select>
                    主页费单价：<InputNumber min={0} value={homeFee} onChange={this.onChangeHomeFee}/>
                    续页费币种：<Select placeholder="请选择币种" value={sheetCurrency} onChange={this.changeSheetCurrency}
                                  style={{width: "100px"}}>
                    {currencyList.map((item, index) => (
                        <Option key={index} value={item.name}>
                            {item.name}
                        </Option>
                    ))}
                </Select>
                    续页费单价：<InputNumber min={0} value={sheetFee} onChange={this.onChangeSheetFee}/>
                </div>
                <div className="actions">
                    <Button onClick={this.handleAddFeeName}><Icon
                        type="add"/>加一行费用</Button>
                </div>
                <Table
                    {...tableProps}
                    tableLayout={'fixed'}
                    columns={editColumns}
                    dataSource={[...data]}
                    components={components}
                    loading={loading}
                    rowClassName={() => 'editable-row'}
                />
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.client.clientFee,
        currencyList: state.zadOrder.list.currencyList
    };
};

export default connect(mapStateToProps)(ClientFeeModal);
